<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
</style>

<body>
    <div id="app">
        <input type="checkbox" v-model="isAllCheck">全选
        <div class="box" v-for="(item,index) in list2">
            <input type="checkbox" v-model="item.checked">
            名称：<span>{{ item.name}}</span>
            单价：<span>{{ item.price.toFixed(2)}}</span>
            数量：<button @click="item.num--" :disabled="item.num <=1">-</button>
            <span>{{ item.num.toFixed(2)}}</span>
            <button @click="item.num++" :disabled="item.num >= item.max">+</button>
            金额：<span>{{ (item.price * item.num).toFixed(2)}}</span>
            <button @click="list.splice(index,1)">删除</button>
        </div><br>
        {{ checkedCount }}件商品总计(不含运费): <span>{{totalPrice.toFixed(2)}}</span>

    </div>
</body>
<script src="./vue.js"></script>
<script>
    const { createApp, ref, computed } = Vue
    createApp({
        setup() {
            const val = ref(1)
            const list = ref([{
                name: "西瓜",
                price: 5,
                num: 1,
                max: 100,
                checked: false
            }, {
                name: "提子",
                price: 12,
                num: 5,
                max: 50,
                checked: true

            }, {
                name: "榴莲",
                price: 29.9,
                num: 1,
                max: 20,
                checked: false
            }])

            const list2 = computed(() => {
                return list.value.map(v => {
                    v.total = v.checked ? (v.price * v.num) * val.value : 0;
                    return v
                })
            })

            const isAllCheck = computed({
                get: () => list2.value.every(item => item.checked), //检查list2里面的checked是否全部是true 用于判断是否全部选中
                set: (val) => {
                    list.value.forEach(item => {
                        item.checked = val
                    })
                }
            })

            const totalPrice = computed(() => list2.value.reduce((total, item) => total + (item.checked ? item.total : 0), 0))
            const checkedCount = computed(() => list.value.filter(item => item.checked).length)

            return {
                val,
                list,
                list2,
                totalPrice,
                isAllCheck,
                checkedCount
            }
        }
    }).mount("#app")
</script>

</html>